package com.campus.help.controller;

import com.campus.help.common.Result;
import com.campus.help.utils.FileStorageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 *
 * @author campus-help
 * @since 2025-10-15
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private FileStorageUtils fileStorageUtils;

    /**
     * 获取上传凭证（简化版本，直接返回上传接口信息）
     */
    @GetMapping("/token")
    public Result<Map<String, String>> getUploadToken() {
        try {
            Map<String, String> result = new HashMap<>();
            result.put("uploadUrl", "/api/upload/file");
            result.put("key", "file");
            result.put("policy", "");
            result.put("signature", "");

            log.info("生成上传凭证成功");
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取上传凭证失败：{}", e.getMessage(), e);
            return Result.error("获取上传凭证失败");
        }
    }

    /**
     * 直接上传文件
     */
    @PostMapping("/file")
    public Result<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只支持图片文件");
            }

            // 上传文件
            String fileName = fileStorageUtils.uploadFile(file, "images");
            String fileUrl = fileStorageUtils.getFileUrl(fileName);

            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("key", fileName);
            result.put("success", "true");

            log.info("文件上传成功：{}", fileName);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件上传失败：{}", e.getMessage(), e);
            return Result.error("文件上传失败");
        }
    }
}
